
import 'dart:convert';
import 'package:baselib/base/login_out_event.dart';
import 'package:event_bus/event_bus.dart';
import 'package:baselib/base/base_responce.dart';
import 'package:dio/dio.dart';
import 'package:flutter/widgets.dart';
import 'dart:convert' as convert;
import '../http/dio_init.dart';
///网络请求封装
class CommonApiService{
  static EventBus eventBus = new EventBus();
  static Future<BaseResponce> _request(BuildContext context, Future<Response> future) {
    assert(() {
      try {
        if (context != null && Navigator.of(context) == null) {
          throw 'context必须是Scaffold的context';
        }
      } catch (error) {
        throw error.toString();
      }
      return true;
    }());
    return future.then((response) {

      if(response.data==null){
        return null;
      }else {
        BaseResponce baseResponce=BaseResponce.fromJson(response.data);
        if(baseResponce.code==4002){
          eventBus.fire(LoginOutEvent());
        }
        return baseResponce;
      }
    });
  }

  static Future requestGet(
      BuildContext context, {
        @required String url,
        dynamic data,
      }) {
    return _request(context, HttpUtil.getInstance().dio.get(url, queryParameters: data));
  }

  static Future requestPost(
      BuildContext context, {
        @required String url,
        dynamic data,
      }) {
    return _request(context, HttpUtil.getInstance().dio.post(url, data: data));
  }

  static Future requestDelete(
      BuildContext context, {
        @required String url,
        dynamic data,
      }) {
    return _request(context, HttpUtil.getInstance().dio.delete(url, data: data));
  }

  static Future requestPut(
      BuildContext context, {
        @required String url,
        dynamic data,
      }) {
    return _request(context, HttpUtil.getInstance().dio.put(url, data: data));
  }
}